package cn.zhl.collector;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

/**
 * @program: demos
 * @description: 自定义收集器
 * 注意：Characteristics.IDENTITY_FINISH  表示中间结果和返回结果相同
 * @author: 刘振华
 * @create: 2020-04-24 08:35
 **/
public class MyMapCollector<T> implements Collector<T, Set<T>, Map<T, T>> {
	public static void main(String[] args) {
//        List<String> list = Arrays.asList("hello my name is a b c d e f g ha mei lilei".split(" "));
//        Map<String, String> cs = list.parallelStream().collect(new MyMapCollector<>());
//        System.out.println(cs);
		System.out.println(Runtime.getRuntime().availableProcessors());
	}

	@Override
	public Supplier<Set<T>> supplier() {
		return HashSet::new;
	}

	@Override
	public BiConsumer<Set<T>, T> accumulator() {
		return (a, b) -> {
			System.out.println("accumulator:" + a + "," + Thread.currentThread().getName());
			a.add(b);
		};
	}

	@Override
	public BinaryOperator<Set<T>> combiner() {
		return (a, b) -> {
			System.out.println("combiner:" + a + "," + Thread.currentThread().getName());
			a.addAll(b);
			return a;
		};
	}

	@Override
	public Function<Set<T>, Map<T, T>> finisher() {
		return a -> {
			HashMap<T, T> rs = new HashMap<>();
			a.stream().forEach(b -> rs.put(b, b));
			return rs;
		};
	}

	@Override
	public Set<Characteristics> characteristics() {
		return EnumSet.of(Characteristics.UNORDERED, Characteristics.CONCURRENT);
	}





    /*@Override
    public Supplier<Map<T, R>> supplier() {
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<T, R>, T> accumulator() {
        return (map,s)->map.put(s,(R)R.builder().name(s.toString()).build());
    }

    @Override
    public BinaryOperator<Map<T, R>> combiner() {
        return (a,b)->{
            a.putAll(b);
            return a;
        };
    }

    @Override
    public Function<Map<T, R>, Map<T, R>> finisher() {
        return a->a;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return EnumSet.of(Characteristics.IDENTITY_FINISH,Characteristics.UNORDERED);
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("a","b","c","a");
        Map<String, Person> cs = list.stream().collect(new MyMapCollector<String, Person>());
        cs.forEach((a,b)->{
            System.out.print(a);
            System.out.print(":");
            System.out.println(b);
        });
    }*/
}
